package com.samnative.pineapple.main;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.samnative.pineapple.entity.LoginModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.utils.MD5Util;
import com.shashank.sony.fancytoastlib.FancyToast;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import ezy.ui.view.RoundButton;


/**
 * 登录==》账号密码登录
 *
 * @author wangy
 */
public class LoginActivity extends BaseActivity implements OnClickListener {

    /**
     * 输入手机号
     */
    private EditText etPhone, et_pwd;

    /**
     * 登陆按钮
     */
    private RoundButton btnLogin;


    public static LoginActivity instance = null;

    private TextView find_pwd_tv;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        // TODO Auto-generated method stub
        findViewById(R.id.close_iv).setOnClickListener(this);

        etPhone = (EditText) findViewById(R.id.et_phone);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        find_pwd_tv = (TextView) findViewById(R.id.find_pwd_tv);
        find_pwd_tv.setOnClickListener(this);
        btnLogin = (RoundButton) findViewById(R.id.btn_login);
        findViewById(R.id.tv_register).setOnClickListener(this);
        find(R.id.tv_yzm_login).setOnClickListener(this);

        //设置显示或隐藏密码
        ((CheckBox) findViewById(R.id.ib_change_pw)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    et_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    et_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                et_pwd.setSelection(et_pwd.getText().length());
            }
        });

        btnLogin.setOnClickListener(this);
        phoneChange();
        pwdChange();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.close_iv:
                finish();
                break;
            case R.id.find_pwd_tv://找回密码
                startActivity(new Intent()
                        .putExtra("type", 2)
                        .setClass(mContext, PasswordLoginVerityActivity.class));
                break;
            case R.id.btn_login:
                if (etPhone.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.input_phone), FancyToast.WARNING, false);
                    return;
                }
                if (et_pwd.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.input_pwd), FancyToast.WARNING, false);
                } else {
                    doLogin();
                }
                break;
//            case R.id.protocol_tv:
////                startActivity(new Intent(context,
////                        RegistrationProtocolActivity.class));
//                Intent intent = new Intent(context, WebViewActivity.class);
//                intent.putExtra("url", ConstsObject.web_url + "Introduction/index/registDeal");
//                startActivity(intent);
//                break;
            case R.id.tv_register: {
                Intent intent = new Intent(mContext, RegisterActivity.class);
                startActivity(intent);
            }
            break;
//            case R.id.iv_clear:
//                etPhone.getText().clear();
//                break;
            case R.id.tv_yzm_login: {
                Intent intent = new Intent(mContext, LoginForCodeActivity.class);
                startActivity(intent, false);
                finish(R.anim.act_web_back1, R.anim.act_web_back2);
            }
            break;
            default:
                break;
        }
    }

    /**
     * 执行登录
     */
    private void doLogin() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", etPhone.getText().toString().trim());
        map.put("password", MD5Util.getMD5Str(et_pwd.getText().toString().trim()));
        HttpRequest.request(this, "/client/user/login","", map,"POST", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    AppPrefer.getInstance(mContext).put(AppPrefer.mtoken, result.getString("token"));
                    AppPrefer.getInstance(mContext).put(AppPrefer.isPrivacyPolicy, true);
                    showUserInfo();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);

            }

        });
    }

    /**
     * 获取用户信息
     */
    public void showUserInfo() {
        try {
            Map<String, String> map = new HashMap<>();
            HttpRequest.request(this, "/client/user/userinfo","", map,"POST", new JsonResult() {
                @Override
                public void reqestSuccess(JSONObject result) {
                    try {
                        AppPrefer.getInstance(mContext).put(AppPrefer.userinfo, result.toString());

                        //正常登录情况
                        Intent intent = new Intent().setClass(mContext, MainActivity.class);
                        intent.putExtra("relogin", true);
                        startActivity(intent);
                        finish();


                        if (LoginActivity.instance != null) {
                            LoginActivity.instance.finish();
                        }

                        if (RegisterActivity.instance != null) {
                            RegisterActivity.instance.finish();
                        }

                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    //-------------------------------------监听开始---------------------------------------------

    /**
     * 手机输入框监听
     */
    private void phoneChange() {
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (etPhone. getText().toString().length() < 6 || et_pwd.length() < 6) {
//                    btnLogin.setBackground(getResources().getDrawable(
//                            R.drawable.login_btn_selector3));
//                    btnLogin.setTextColor(getResources().getColor(R.color.main_gray_bg));
                } else {
//                    btnLogin.setBackground(getResources().getDrawable(
//                            R.drawable.login_btn_selector));
//                    btnLogin.setTextColor(getResources().getColor(R.color.main_white));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 密码监听
     */
    private void pwdChange() {
        et_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if (mobile.length() < 6 || pwd.length() < 6) {
//                    btnLogin.setBackground(getResources().getDrawable(
//                            R.drawable.login_btn_selector3));
//                    btnLogin.setTextColor(getResources().getColor(R.color.main_gray_bg));
////                    btnLogin.setClickable(false);
//                } else {
//                    btnLogin.setBackground(getResources().getDrawable(
//                            R.drawable.login_btn_selector));
//                    btnLogin.setTextColor(getResources().getColor(R.color.main_white));
////                    btnLogin.setClickable(true);
//                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

}
